package com.seekting.mynews.connect.tiangou.bean.request;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.seekting.mynews.App;
import com.seekting.mynews.R;
import com.seekting.mynews.connect.tiangou.bean.response.TianGouShow;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

public class TianGouShowRequest extends UIDRequest<TianGouShow> {

    private Listener<TianGouShow> mListener;
    private int cacheDay;
    public static final String URL;

    static {
        URL = App.getApp().getString(R.string.tngou_show_url);
    }

    public static String getUrl(int id) {
        String str = String.format(URL, id);
        return str;
    }

    public TianGouShowRequest(String url, Listener<TianGouShow> listener, ErrorListener errListener) {
        this(Method.GET, url, errListener);
        mListener = listener;
        setShouldCache(true);
        this.cacheDay = App.getApp().getResources().getInteger(R.integer.tngou_show_cache_days);

    }

    public TianGouShowRequest(int method, String url, ErrorListener errorListener) {
        super(method, url, errorListener);
    }

    @Override
    public Response<TianGouShow> parseNetworkResponse(NetworkResponse response) {
        String str;
        try {
            str = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            str = new String(response.data);
        }
        JSONObject json = JSONObject.parseObject(str);
        TianGouShow TianGouShow = JSONObject.toJavaObject(json, TianGouShow.class);
        TianGouShow.setUuid(getUUid());

        //加上过期时间
        long time = TimeUnit.DAYS.toSeconds(cacheDay);
        response.headers.put("Cache-Control", "max-age=" + time);
        return Response.success(TianGouShow, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(TianGouShow response) {
        mListener.onResponse(response);
    }

}
